package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.XieWanGaoUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.ec.v2.config.Config;
import com.ec.v2.service.GeneralDemo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * My
 */
@Service
public class QingFuYingApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();
        long timeStamp = System.currentTimeMillis();
        String timeStampString = Long.toString(timeStamp);

        String appId = pushApiKeyParam.getApiKey();
        String appSecret = pushApiKeyParam.getApiSecret();
        String sign = getSign(timeStamp, appId, appSecret);


        List<String> list = new ArrayList<>();
        list.add("name");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("mobile", memberSourceInfo.getMobile());
        paramMap.put("maxNumsPreMobile", 1);
        paramMap.put("includes", list);

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        headMap.put("X-Ec-Cid", pushApiKeyParam.getApiCode());
        headMap.put("X-Ec-Sign", sign);
        headMap.put("X-Ec-TimeStamp", timeStampString);

        log.info("【上海青蚨盈】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(headMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .headerMap(headMap, true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【上海青蚨盈】撞库结束【result】{}", result);
        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode("|" + code);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(headMap));
        pushApiResult.setResultInfo(resultObject.toJSONString());

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
        }
//        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        String timeStampString = Long.toString(System.currentTimeMillis());

        String appId = pushApiKeyParam.getApiKey();
        String appSecret = pushApiKeyParam.getApiSecret();
        String sign = getSign(Long.valueOf(timeStampString), appId, appSecret);

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        headMap.put("X-Ec-Cid", pushApiKeyParam.getApiCode());
        headMap.put("X-Ec-Sign", sign);
        headMap.put("X-Ec-TimeStamp", timeStampString);
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createDate = memberSourceInfo.getCreateTime().format(fmt);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("optUserId",19051641);
        JSONArray objects = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("followUserId",Long.valueOf(pushApiKeyParam.getPriKey()));
        jsonObject.put("name",memberSourceInfo.getRealname());
        jsonObject.put("gender",memberSourceInfo.getSex());
        jsonObject.put("birthday",getBirthFromIdCard(memberSourceInfo.getIdcard()));
        jsonObject.put("mobile",memberSourceInfo.getMobile());
        jsonObject.put("memo",
                "客户要贷款：" + BaseTypeInfoEnum.LoanAmount.getNameByValue(memberSourceInfo.getLoanAmount()) + "  " + BaseTypeInfoEnum.LoanTime.getNameByValue(memberSourceInfo.getLoanTime()) + "||"
                + "申请时间：" + createDate
                + "车产情况：" + BaseTypeInfoEnum.Car.getNameByValue(memberSourceInfo.getCar()) + "||"
                + "房车情况：" + BaseTypeInfoEnum.House.getNameByValue(memberSourceInfo.getHouse()) + "||"
                + "公积金情况：" + BaseTypeInfoEnum.Gjj.getNameByValue(memberSourceInfo.getGjj()) + "||"
                + "逾期情况：" + BaseTypeInfoEnum.Yuqi.getNameByValue(memberSourceInfo.getYuqi()) + "||"
//                + "贷款时间：" + BaseTypeInfoEnum.LoanTime.getNameByValue(memberSourceInfo.getLoanTime()) + "||"
//                + "贷款金额：" + BaseTypeInfoEnum.LoanAmount.getNameByValue(memberSourceInfo.getLoanAmount()) + "||"
        );
        jsonObject.put("channelId",pushApiKeyParam.getPubKey());
        StringBuilder prefecture = new StringBuilder();

        prefecture.append("中国").append("|").append(memberSourceInfo.getProvince()).append("|").append(memberSourceInfo.getCity());
//        prefecture.append("中国|上海市|上海市");
        jsonObject.put("prefecture",prefecture.toString());
        objects.add(jsonObject);
        paramMap.put("list",objects);
//        paramMap.put("notify",false);

//        paramMap.put("userId", pushApiKeyParam.getPriKey());
//        paramMap.put("name", memberSourceInfo.getRealname());
//        paramMap.put("phone", memberSourceInfo.getMobile());
//        paramMap.put("source", pushApiKeyParam.getPubKey());
//        paramMap.put("country", 100000);
//        paramMap.put("province", Integer.valueOf(memberSourceInfo.getProvinceCode()));
//        paramMap.put("city", Integer.valueOf(memberSourceInfo.getCityCode()));
//        paramMap.put("region", Integer.valueOf(memberSourceInfo.getCityCode()));
//        paramMap.put("remark",
//                "车产情况：" + BaseTypeInfoEnum.Car.getNameByValue(memberSourceInfo.getCar()) + "||"
//                + "房车情况：" + BaseTypeInfoEnum.House.getNameByValue(memberSourceInfo.getHouse()) + "||"
//                + "公积金情况：" + BaseTypeInfoEnum.Gjj.getNameByValue(memberSourceInfo.getGjj()) + "||"
//                + "逾期情况：" + BaseTypeInfoEnum.Yuqi.getNameByValue(memberSourceInfo.getYuqi())
//        );

        log.info("【上海青蚨盈】导单开始【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .headerMap(headMap, true)
                .execute().body();
        log.info("【上海青蚨盈】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode("|" + code);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    /**
     * @param timeStamp 时间戳
     * @param appId
     * @param appSecret 秘钥
     * @return
     * @Title: getSign
     * @Description: 生成签名
     * @author shicy
     * @date 2020-03-23 11:32:03
     */
    public static String getSign(long timeStamp, String appId, String appSecret) {
        //签名过期
        StringBuffer buffer = new StringBuffer();
        buffer.append("appId=" + appId);
        buffer.append("&appSecret=" + appSecret);
        buffer.append("&timeStamp=" + timeStamp);
        return encryptMd5(buffer.toString()).toUpperCase();
    }


    /**
     * MD5加密
     *
     * @param sourceStr
     * @return
     */
    public static String encryptMd5(String sourceStr) {
        // 用于加密的字符
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取出生日期
     *
     * @return 返回字符串类型
     */
    public String getBirthFromIdCard(String idCard) {
        if (idCard.length() != 18 && idCard.length() != 15) {
            return null;
        }
        if (idCard.length() == 18) {
            String year = idCard.substring(6).substring(0, 4);// 得到年份
            String month = idCard.substring(10).substring(0, 2);// 得到月份
            String day = idCard.substring(12).substring(0, 2);// 得到日
            return (year + "-" + month + "-" + day);
        } else if (idCard.length() == 15) {
            String year = "19" + idCard.substring(6, 8);// 年份
            String month = idCard.substring(8, 10);// 月份
            String day = idCard.substring(10, 12);// 得到日
            return (year + "-" + month + "-" + day);
        }
        return null;
    }

}
